package cn.cdtu.tibetplan.service.impl;

import java.util.List;

import cn.cdtu.tibetplan.mapper.QuestionMapper;
import cn.cdtu.tibetplan.pojo.PageResult;
import cn.cdtu.tibetplan.pojo.Question;
import cn.cdtu.tibetplan.pojo.QuestionExample;
import org.springframework.beans.factory.annotation.Autowired;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.cdtu.tibetplan.pojo.QuestionExample.Criteria;
import cn.cdtu.tibetplan.service.QuestionService;


import org.springframework.stereotype.Service;

/**
 * 服务实现层
 *
 * @author Administrator
 */
@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    /**
     * 查询全部
     */
    @Override
    public List<Question> findAll() {
        return questionMapper.selectByExample(null);
    }

    /**
     * 按分页查询
     */
    @Override
    public PageResult findPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<Question> page = (Page<Question>) questionMapper.selectByExample(null);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 增加
     */
    @Override
    public void add(Question question) {
        questionMapper.insert(question);
    }


    /**
     * 修改
     */
    @Override
    public void update(Question question) {
        questionMapper.updateByPrimaryKey(question);
    }

    /**
     * 根据ID获取实体
     *
     * @param id
     * @return
     */
    @Override
    public Question findOne(Long id) {
        return questionMapper.selectByPrimaryKey(id.intValue());
    }

    /**
     * 批量删除
     */
    @Override
    public void delete(Long[] ids) {
        for (Long id : ids) {
            questionMapper.deleteByPrimaryKey(id.intValue());
        }
    }


    @Override
    public PageResult findPage(Question question, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        QuestionExample example = new QuestionExample();
        Criteria criteria = example.createCriteria();

        if (question != null) {
            if (question.getQuestion() != null && question.getQuestion().length() > 0) {
                criteria.andQuestionLike("%" + question.getQuestion() + "%");
            }
            if (question.getAnswer() != null && question.getAnswer().length() > 0) {
                criteria.andAnswerLike("%" + question.getAnswer() + "%");
            }
            if (question.getOther1() != null && question.getOther1().length() > 0) {
                criteria.andOther1Like("%" + question.getOther1() + "%");
            }

        }

        Page<Question> page = (Page<Question>) questionMapper.selectByExample(example);
        return new PageResult(page.getTotal(), page.getResult());
    }

}
